package weeny.pre.io.parser;

import java.awt.BasicStroke;
import java.awt.Stroke;
import java.util.regex.Pattern;

import prefuse.data.parser.DataParseException;
import prefuse.data.parser.DataParser;
import prefuse.data.parser.FloatArrayParser;
import prefuse.util.StrokeLib;

//WEENY added
public class StrokeParser implements DataParser{
	public boolean canParse(String text) {
		try {
			parse(text);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean compatible(Class type) {
//		return type.isAssignableFrom(getType());
		return getType().isAssignableFrom(type);
	}
	public static FloatArrayParser fap = new FloatArrayParser();
	public static final String HEAD  = "STROKE";
	public static final String VALUE = ":value=";
	static Pattern split = Pattern.compile("(?:"+VALUE+")");
	public String format(Object value) {
		if (value == null) {
			return "";
		}
		BasicStroke stk = (BasicStroke) value;
		StringBuffer sb = new StringBuffer();
		int dash = (stk.getDashArray()==null? 0 : stk.getDashArray().length);
		float[] result = new float[5+ dash];
		result[0] = stk.getLineWidth();
		result[1] = stk.getDashPhase();
		result[2] = stk.getEndCap();
		result[3] = stk.getLineJoin();
		result[4] = stk.getMiterLimit();
		for(int i = 5; i<result.length; i++){
			result[i] = stk.getDashArray()[i-5];
		}
		sb.append(HEAD);sb.append(VALUE);
		sb.append(fap.format(result));
		return sb.toString();
	}

	public Class getType() {
		return Stroke.class;
	}

	public Object parse(String text) throws DataParseException {
		String[] tokens = split.split(text);
		if (tokens.length == 2 && tokens[0].equals(HEAD)) {
			float[] v = (float[]) fap.parse(tokens[1]);
			float[] d = null;
			d = new float[v.length-5];
			for(int i = 0; i<d.length; i++){
				d[i] = v[5+i];
			}
			if (d.length == 0) {
				d = null;
			}
			return StrokeLib.getStroke(v[0],(int)v[2], (int)v[3], (int)v[4], d, v[1]);
		}
		throw new DataParseException(text+" does not match "+split.pattern());
	}
}
